package com.shen.server;

import com.shen.user.User;

import java.io.*;

/**
 * Author:shen
 * CreateDate:2020/6/9.
 * Function:
 */
public class UserService {
    /**
     * 获得序列化用户信息
     */
    public  User[] getSerializUser(){
        User[] users=null;
        ObjectInputStream objectInputStream=null;
        FileInputStream fileInputStream=null;
        try {
            fileInputStream=new FileInputStream("user.txt");
            objectInputStream=new ObjectInputStream(fileInputStream);
            users = (User[]) objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(objectInputStream!=null){
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return users;
    }

    /**
     * 检测是否存在该用户
     * @return
     */
    public boolean checkUser(User user){
        boolean isflag=false;
        User[] serializUser =  getSerializUser();
        for (User userSer : serializUser) {
            if((userSer.getName().equals(user.getName()))&&(user.getPassword().equals(user.getPassword()))){
                isflag=true;
            }
        }
        return isflag;
    }
    /**
     * 序列化用户信息
     */
    public  void toSerializUser(User[] user){
        ObjectOutput objectOutput=null;
        FileOutputStream fileOutputStream=null;
        try {
            fileOutputStream=new FileOutputStream("user.txt",true);
            objectOutput=new ObjectOutputStream(fileOutputStream);
            objectOutput.writeObject(user);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(objectOutput!=null){
                try {
                    objectOutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        /**
         * 序列化多个用户
         */
        User[] users={new User("小明","123"),new User("shen2","1234")};
        UserService userService=new UserService();
        userService.toSerializUser(users);
        User[] serializUser = userService.getSerializUser();
        for (Object o : serializUser) {
            System.out.println(o);
        }
    }
}
